package com.huanxing.cloud.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.product.api.remote.RemoteGoodsSpuService;
import com.huanxing.cloud.product.api.entity.GoodsSpu;
import com.huanxing.cloud.shop.api.dto.ShopInfoDTO;
import com.huanxing.cloud.shop.api.entity.ShopInfo;
import com.huanxing.cloud.shop.api.vo.ShopInfoVO;
import com.huanxing.cloud.shop.mapper.ShopInfoMapper;
import com.huanxing.cloud.shop.service.IShopInfoService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺
 *
 * @author lijx
 * @date 2024/05/07 13:07
 */
@Service
@RequiredArgsConstructor
public class ShopInfoServiceImpl extends ServiceImpl<ShopInfoMapper, ShopInfo> implements IShopInfoService {

	@DubboReference
	private final RemoteGoodsSpuService remoteGoodsSpuService;

	@Override
	public IPage<ShopInfoVO> getPage(Page page, ShopInfoDTO shopInfoDTO) {
		IPage<ShopInfoVO> iPage = baseMapper.selectShopPage(page, shopInfoDTO);
		if (CollectionUtils.isEmpty(iPage.getRecords())) {
			return iPage;
		}
		// 从List中提取店铺ID
		List<String> shopIds = iPage.getRecords().stream().map(ShopInfoVO::getShopId).toList();

		// 调用商品服务，获取商品详情
		List<GoodsSpu> goodsSpuList = remoteGoodsSpuService.getSpuListByShopIds(shopIds);
		if (CollectionUtils.isEmpty(goodsSpuList)) {
			throw new IllegalArgumentException("query product spu list fail! ");
		}
		// 使用Stream流创建店铺D到商品对象的映射
		Map<String, List<GoodsSpu>> productMap = goodsSpuList.stream()
			.collect(Collectors.groupingBy(GoodsSpu::getShopId));
		iPage.getRecords().forEach(shopInfoVO -> {
			List<GoodsSpu> existGoodsSpuList = productMap.get(shopInfoVO.getShopId());
			if (!CollectionUtils.isEmpty(existGoodsSpuList)) {
				shopInfoVO.setGoodsSpuList(existGoodsSpuList);
			}
		});
		return iPage;
	}

	@Override
	public List<ShopInfoVO> getShopByIds(List<String> ids) {
		List<ShopInfo> shopInfoList = this.listByIds(ids);
		if (!CollectionUtils.isEmpty(shopInfoList)) {
			return shopInfoList.stream().map(v -> {
				ShopInfoVO shopInfoVO = new ShopInfoVO();
				shopInfoVO.setShopId(v.getShopId());
				shopInfoVO.setName(v.getName());
				shopInfoVO.setLogoUrl(v.getLogoUrl());
				shopInfoVO.setType(v.getType());
				return shopInfoVO;
			}).collect(Collectors.toList());
		}
		return null;
	}

}
